package com.sky.controller;

import com.google.code.kaptcha.Producer;
import com.sky.constant.Const;
import com.sky.domain.Result;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @projectName: netty-cloud
 * @package: com.sky.controller
 * @className: LoginController
 * @author: zhl
 * @description: 登录校验
 * @date: 2024/4/25 10:28
 * @version: 1.0
 */
@Controller
public class LoginController {

    @Resource
    Producer producer;
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/captcha")
    @ResponseBody
    public Result Captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        Base64.Encoder encoder = Base64.getEncoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + new String(encoder.encode(outputStream.toByteArray()));

        redisTemplate.opsForValue().set(Const.CAPTCHA_KEY + key, code,120, TimeUnit.SECONDS);
        HashMap<Object, Object> hashMap = new HashMap<>(16) {{
            put("userKey",key);
            put("captcherImg",base64Img);
        }};
        return Result.success(hashMap);
    }

}
